<template>
  <div class="login bg-neutral-100 font-inter min-h-screen flex items-center justify-center">
    <div class="max-w-md w-full bg-white rounded-xl shadow-lg overflow-hidden">
      <!-- 品牌标识区 -->
      <div class="py-8 px-6 text-center border-b border-neutral-200">
        <div class="flex items-center justify-center mb-4">
          <div class="w-16 h-16 bg-primary rounded-full flex items-center justify-center text-white text-2xl">
            <i class="fa fa-shield"></i>
          </div>
        </div>
        <h1 class="text-2xl font-bold text-neutral-700">昌吉回族自治州机动车监管平台</h1>
      </div>

      <!-- 登录方式选择区 -->
      <div class="p-6">
        <div class="flex border-b border-neutral-200 mb-6">
          <!-- <button class="flex-1 py-3 text-center tab-active" @click="activeTab = 'iam'">
            <i class="fa fa-key mr-2"></i> IAM登录
          </button> -->
          <button class="flex-1 py-3 text-center tab-inactive" @click="activeTab = 'internal'">
            <i class="fa fa-building-o mr-2"></i> 内部系统登录
          </button>
        </div>

        <!-- 登录表单区域 -->
        <div class="space-y-4">
          <!-- IAM登录表单 -->
          <div v-show="activeTab === 'iam'" class="animate-fade-in">
            <div class="space-y-4">
              <div>
                <label class="block text-sm font-medium text-neutral-500 mb-1">用户名/邮箱</label>
                <div class="relative">
                  <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                    <i class="fa fa-user"></i>
                  </span>
                  <input type="text"
                    class="w-full pl-10 pr-4 py-2 border border-neutral-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                    placeholder="请输入用户名或邮箱" v-model="iamUsername">
                </div>
              </div>

              <div>
                <div class="flex justify-between items-center mb-1">
                  <label class="block text-sm font-medium text-neutral-500">密码</label>
                  <button type="button" class="text-xs text-primary hover:text-primary/80 transition-colors">
                    忘记密码?
                  </button>
                </div>
                <div class="relative">
                  <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                    <i class="fa fa-lock"></i>
                  </span>
                  <input :type="iamShowPassword ? 'text' : 'password'"
                    class="w-full pl-10 pr-10 py-2 border border-neutral-200 rounded-lg focus:border-primary focus:ring-1 focus:ring-primary outline-none transition-all"
                    placeholder="请输入密码" v-model="iamPassword">
                  <button type="button"
                    class="absolute inset-y-0 right-0 flex items-center pr-3 text-neutral-400 hover:text-neutral-600 transition-colors"
                    @click="iamShowPassword = !iamShowPassword">
                    <i :class="iamShowPassword ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
                  </button>
                </div>
              </div>

              <div class="flex items-center">
                <input type="checkbox" id="iamRemember"
                  class="w-4 h-4 text-primary border-neutral-300 rounded focus:ring-primary" v-model="iamRemember">
                <label for="iamRemember" class="ml-2 text-sm text-neutral-500">记住账号</label>
              </div>

              <button style="color: black;"
                class="w-full bg-primary text-white py-2.5 px-4 rounded-lg font-medium shadow-md hover:shadow-lg transform hover:-translate-y-0.5 transition-all duration-200"
                @click="loginWithIAM">
                登录
              </button>

              <!-- <div class="flex items-center justify-center mt-4">
                <span class="text-sm text-neutral-400">还没有账号?</span>
                <button class="ml-2 text-sm text-primary hover:text-primary/80 transition-colors">
                  立即注册
                </button>
              </div> -->
            </div>
          </div>

          <!-- 内部系统登录表单 -->
          <div v-show="activeTab === 'internal'" class="animate-fade-in">
            <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
              <div class="space-y-4">
                <div>
                  <label class="block text-sm font-medium text-neutral-500 mb-1">账号登录</label>
                  <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                      <i class="fa fa-id-card-o"></i>
                    </span>
                    <el-form-item prop="userName">
                      <el-input type="text"
                        class=""
                        placeholder="请输入用户名" v-model="loginForm.userName" />
                    </el-form-item>
                  </div>
                </div>

                <div>
                  <div class="flex justify-between items-center mb-1">
                    <!-- <label class="block text-sm font-medium text-neutral-500">内部系统密码</label> -->
                    <!-- <button type="button" class="text-xs text-primary hover:text-primary/80 transition-colors">
                    找回密码
                  </button> -->
                  </div>
                  <div class="relative">
                    <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-neutral-400">
                      <i class="fa fa-lock"></i>
                    </span>
                    <el-form-item prop="password">

                      <el-input type="password"
                        class=""
                        placeholder="请输入密码" v-model="loginForm.password" />
                    </el-form-item>
                    <!-- <button type="button"
                      class="absolute inset-y-0 right-0 flex items-center pr-3 text-neutral-400 hover:text-neutral-600 transition-colors"
                      @click="internalShowPassword = !internalShowPassword">
                      <i :class="internalShowPassword ? 'fa fa-eye-slash' : 'fa fa-eye'"></i>
                    </button> -->
                  </div>
                </div>

                <div class="flex items-center justify-between">
                  <div class="flex">
                    <el-checkbox type="checkbox" id="internalRemember"
                      class=""
                      v-model="loginForm.rememberMe" />
                    <label for="internalRemember" class="ml-2 text-sm text-neutral-500">记住账号</label>
                  </div>
                  <div class="flex items-center">
                    <!-- <input type="checkbox" id="internalAutoLogin"
                    class="w-4 h-4 text-primary border-neutral-300 rounded focus:ring-primary"
                    v-model="internalAutoLogin"> -->
                    <!-- <label for="internalAutoLogin" class="ml-2 text-sm text-neutral-500">自动登录</label> -->
                  </div>
                </div>

                <el-button style="color: black;"
                  class="w-full bg-primary text-white py-2.5 px-4 rounded-lg font-medium shadow-md hover:shadow-lg transform hover:-translate-y-0.5 transition-all"
                  @click="handleLogin">
                  登录
                </el-button>

                <div class="flex items-center justify-center mt-4">
                  <span class="text-sm text-neutral-400">账号申请请联系</span>
                  <div href="mailto:it-support@company.com"
                    class="ml-2 text-sm text-primary hover:text-primary/80 transition-colors">
                    相关部门
                  </div>
                </div>
              </div>
            </el-form>

          </div>
        </div>

        <!-- 其他登录方式 -->
        <div class="mt-8">
          <div class="relative flex items-center justify-center">
            <div class="absolute inset-0 flex items-center">
              <div class="w-full border-t border-neutral-200"></div>
            </div>
            <!-- <div class="relative z-10 px-4 bg-white text-sm text-neutral-400">
              其他登录方式
            </div> -->
          </div>

          <div class="flex justify-center mt-4 space-x-6">
            <button class="text-neutral-400 hover:text-green-500 transition-colors">
              <i class="fa fa-wechat text-xl"></i>
            </button>
            <button class="text-neutral-400 hover:text-blue-500 transition-colors">
              <i class="fa fa-qq text-xl"></i>
            </button>
            <button class="text-neutral-400 hover:text-red-500 transition-colors">
              <i class="fa fa-envelope text-xl"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 页脚 -->
      <div class="py-3 px-6 text-center text-xs text-neutral-400 border-t border-neutral-200">
        Copyright © 2021-2025
      </div>
    </div>
  </div>
</template>

<script>
import { getCodeImg } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import { getCaptcha, getMyToken } from "@/api/largescreen";
import { getToken, setToken, removeToken } from '@/utils/auth'

export default {
  name: "Login",
  data() {
    return {
      captchaUrl: undefined,
      codeUrl: "",
      cookiePassword: "",
      grant_type: 'password',
      platId: 1,
      loginForm: {
        userName: "",
        password: "",
        rememberMe: false,
        token: "",
      },
      loginRules: {
        userName: [
          { required: true, trigger: "blur", message: "用户名不能为空" }
        ],
        password: [
          { required: true, trigger: "blur", message: "密码不能为空" }
        ],
        validateCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' }
        ],
      },
      loading: false,
      redirect: undefined,
      activeTab: 'internal',
      // IAM登录表单数据
      iamUsername: '',
      iamPassword: '',
      iamShowPassword: false,
      iamRemember: false,
      // 内部系统登录表单数据
      internalUserId: '',
      internalPassword: '',
      internalShowPassword: false,
      internalRemember: false,
      internalAutoLogin: false,
      // 登录状态
      errorMessage: ''
    };
  },
  watch: {
    iamRemember(val) {
      if (val) {
        localStorage.setItem('iamRemember', 'true');
        localStorage.setItem('iamUsername', this.iamUsername);
      } else {
        localStorage.removeItem('iamRemember');
        localStorage.removeItem('iamUsername');
      }
    },
    internalRemember(val) {
      if (val) {
        localStorage.setItem('internalRemember', 'true');
        localStorage.setItem('internalUserId', this.internalUserId);
      } else {
        localStorage.removeItem('internalRemember');
        localStorage.removeItem('internalUserId');
      }
    },
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true
    }
  },
  created() {
    if (localStorage.getItem('iamRemember') === 'true') {
      this.iamUsername = localStorage.getItem('iamUsername') || '';
      this.iamRemember = true;
    }

    if (localStorage.getItem('internalRemember') === 'true') {
      this.internalUserId = localStorage.getItem('internalUserId') || '';
      this.internalRemember = true;
    }
    this.getCookie();
  },
  methods: {
    loginWithIAM() {
      if (!this.iamUsername || !this.iamPassword) {
        this.errorMessage = '请输入用户名和密码';
        return;
      }

      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        alert('IAM登录成功！即将跳转到控制台...');
      }, 1000);
    },

    loginWithInternalSystem() {
      if (!this.internalUserId || !this.internalPassword) {
        this.errorMessage = '请输入账号和密码';
        return;
      }

      this.loading = true;
      setTimeout(() => {
        this.loading = false;
        alert('内部系统登录成功！即将跳转到内部系统...');
      }, 1000);
    },
    GetMyToken() {
      getMyToken({
        username: this.loginForm.userName,
        password: this.loginForm.password,
        grant_type: this.grant_type,
      }).then(res => {
        const { access_token, token_type, refresh_token } = res.data
        let storage = window.localStorage;
        let token = token_type + " " + access_token
        setToken('hezuoMJXT', token);

        storage["token_type"] = res.data.token_type;
        storage["access_token"] = res.data.access_token;
        this.$router.push({ path: '/CarScreen' })

      }).catch(err => {
        this.loading = false;
        removeToken("hezuoMJXT")
      })
    },
    getValidateCode() {
      getCaptcha().then(response => {
        const { img, uuid } = response.data
        this.captchaUrl = "data:image/gif;base64," + img
        this.loginForm.uuid = uuid;
      })
    },
    getCookie() {
      const userName = Cookies.get("userName");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      this.loginForm = {
        userName: userName === undefined ? this.loginForm.userName : userName,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {

      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("userName", this.loginForm.userName, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("userName");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          this.GetMyToken();
        }
      });
    }
  }
};
</script>

<style>
.login {

  background: url("../assets/image/background.jpg") no-repeat center/cover ;

}

/* 自定义工具类 */
.animate-fade-in {
  animation: fadeIn 0.3s ease-out forwards;
}

.tab-active {
  color: #165DFF;
  border-bottom: 2px solid #165DFF;
}

.tab-inactive {
  color: #86909C;
}

.tab-inactive:hover {
  color: #165DFF;
  transition: color 0.2s;
}

.form-input-focus {
  border-color: #165DFF;
  box-shadow: 0 0 0 2px rgba(22, 93, 255, 0.2);
}

.btn-hover {
  transition: all 0.2s;
}

.btn-hover:hover {
  box-shadow: 0 4px 12px rgba(22, 93, 255, 0.15);
  transform: translateY(-1px);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(5px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>